﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

using Microsoft.Xna.Framework.Storage;

namespace Hadron
{
    [Serializable]
    public class SaveGame
    {
        private int m_nLives, m_nScore, m_nLevel;

        public SaveGame()
        {
            m_nLives = 3;
            m_nScore = m_nLevel = 0;
        }

        public int Lives
        {
            get { return m_nLives; }
            set { m_nLives = value; }
        }

        public int Score
        {
            get { return m_nScore; }
            set { m_nScore = value; }
        }

        public int Level
        {
            get { return m_nLevel; }
            set { m_nLevel = value; }
        }

        public void Save(StorageDevice p_storageDevice)
        {
            if (p_storageDevice == null)
                return;

            StorageContainer storageContainer = p_storageDevice.OpenContainer("Hadron");
            String strFilename = Path.Combine(storageContainer.Path, "SaveGame.xml");
            FileStream fileStream = File.OpenWrite(strFilename);
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(SaveGame));
            xmlSerializer.Serialize(fileStream, this);
            fileStream.Close();
        }

        public void Load(StorageDevice p_storageDevice)
        {
            if (p_storageDevice == null)
                return;

            StorageContainer storageContainer = p_storageDevice.OpenContainer("Hadron");
            String strFilename = Path.Combine(storageContainer.Path, "SaveGame.xml");

            if (!File.Exists(strFilename))
            {
                m_nLives = 3;
                m_nLevel = 0;
                m_nScore = 0;
                return;
            }

            SaveGame saveGame = new SaveGame();
            FileStream fileStream = null;
            try
            {
                fileStream = File.OpenRead(strFilename);
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(SaveGame));
                saveGame = (SaveGame)xmlSerializer.Deserialize(fileStream);
                fileStream.Close();
            }
            catch (Exception)
            {
                if (fileStream != null)
                    fileStream.Close();
                m_nLives = 3;
                m_nLevel = 0;
                m_nScore = 0;
                return;
            }

            m_nLives = saveGame.Lives;
            m_nScore = saveGame.Score;
            m_nLevel = saveGame.Level;
        }
    }
}
